package com.chebaohui.iqs.service.impl.deal.libao.sdk;

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

/**
 * 利宝请求
 * 
 * @author xielonghai
 *
 */
public class LibaoRequest {

	/**
	 * okhttp-post:form表单形式
	 * 
	 * @param url
	 * @param json
	 * @return
	 * @throws IOException
	 */
	public static String post(String url, RequestBody json) {
		try {
			OkHttpClient client = new OkHttpClient();
			client.setConnectTimeout(2000, TimeUnit.SECONDS);
			client.setReadTimeout(2000, TimeUnit.SECONDS);
			client.setWriteTimeout(2000, TimeUnit.SECONDS);
			Request request = new Request.Builder().url(url).post(json).build();
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				return response.body().string();
			} else {
				return null;
			}
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * okhttp-post:JSON形式
	 * 
	 * @param url
	 * @param json
	 * @return
	 * @throws IOException
	 */
	public static String post(String url, String json) {
		try {
			OkHttpClient client = new OkHttpClient();
			client.setConnectTimeout(20000, TimeUnit.SECONDS);
			client.setReadTimeout(20000, TimeUnit.SECONDS);
			client.setWriteTimeout(20000, TimeUnit.SECONDS);

			RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json);
			Request request = new Request.Builder().url(url).post(body).build();
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				return response.body().string();
			} else {
				return null;
			}
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * okhttp-post:表单形式
	 * 
	 * @param url
	 * @param fromBody
	 * @return
	 */
	public static String postForm(String url, RequestBody fromBody) {
		try {
			OkHttpClient client = new OkHttpClient();
			// 携带表单参数
			Request request = new Request.Builder().url(url).post(fromBody).build();
			Response response = client.newCall(request).execute();
			if (response.isSuccessful()) {
				return response.body().string();
			} else {
				return null;
			}
		} catch (Exception e) {
			return null;
		}
	}

	public static RequestBody getFormBody(Map<String, String> map) {
		FormEncodingBuilder formBody = new FormEncodingBuilder();
		for (String key : map.keySet()) {
			formBody.add(key, map.get(key));
		}
		return formBody.build();
	}

	public static RequestBody getFormBody(JSONObject json) {
		FormEncodingBuilder formBody = new FormEncodingBuilder();
		for (Entry<String, Object> i : json.entrySet()) {
			formBody.add(i.getKey(), null == i.getValue() ? "" : i.getValue().toString());
		}
		return formBody.build();
	}
}
